﻿// 
// FileInfo
// Creater:  程邵磊
// FileName:  JsonEnumConverter.cs
// CreateTime:  2019-02-14
// Remark：

using System;
using Newtonsoft.Json;

namespace Groove.Core.Infrastructure
{
    /// <summary>
    /// Customized Json Enum Converter
    /// Convert normal enum to string and enum with Flags attribute to int
    /// </summary>
    public class JsonEnumConverter : JsonConverter
    {
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            var hasFlagsAttr = HasFlagsAttribute(value);
            if (hasFlagsAttr)
                writer.WriteValue(value);
            else
                writer.WriteValue(value.ToString());
        }

        private bool HasFlagsAttribute(object value)
        {
            return value.GetType().GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;
        }

        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            return reader.Value;
        }

        /// <inheritdoc />
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsEnum;
        }
    }
}